package com.mit.wx.util;

import com.mit.wx.dto.AdminDto;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 2018/10/20 Create by 郭文梁
 * AccessAuthUtil
 * 访问权限及安插工具
 *
 * @author 郭文梁
 * @date 2018/10/20
 */
public class AccessAuthUtil {
    public static boolean checkAuth(HttpServletRequest request) {
        return checkCookie(request);
    }

    private static boolean checkCookie(HttpServletRequest request) {
        HttpSession session = request.getSession();

        Cookie[] cookies = request.getCookies();
        Map<String, String> cookieMap = Arrays.stream(cookies)
                .filter(ck -> ck != null && ck.getName() != null && ck.getValue() != null)
                .collect(Collectors.toMap(Cookie::getName, Cookie::getValue));
        String cookieValue = cookieMap.get(AdminDto.COOKIE_NAME);
        if (cookieValue == null) {
            return false;
        }
        Object result = session.getAttribute(cookieValue);
        return result != null && result instanceof AdminDto && checkSession(session, (AdminDto) result);
    }

    private static boolean checkSession(HttpSession session, AdminDto admin) {
        return admin.equals(session.getAttribute(AdminDto.IN_SESSION_NAME));
    }

    public static void grant(HttpServletRequest request, HttpServletResponse response, AdminDto admin) {
        String randomUUID = UUID.randomUUID().toString();
        HttpSession session = request.getSession();
        session.setAttribute(AdminDto.IN_SESSION_NAME, admin);
        session.setAttribute(randomUUID, admin);
        Cookie cookie = new Cookie(AdminDto.COOKIE_NAME, randomUUID);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
